<template>
  <div class="dialog__body">
    <p style="text-indent: 2em">
      <!-- 根据废气处理设备的A、B、C三相有功功率和设备总有功功率及其相关参数的特征变化和对应的故障类型的历史数据进行训练，采用基于机器学习算法随机森林训练生成的故障诊断模型。 -->
      {{ rowData.purpose }}
    </p>
    <div class="tab-group">
      <hr />
      <div style="display: flex">
        <div style="width: 50%; padding-right: 5px">
          <div class="title">
            <div>
              <span>算法输入数据</span>
              <span v-if="rowData.testFileName"
                >：{{ rowData.testFileName }}</span
              >
            </div>
            <div class="model-button-group">
              <div @click="handleExcute" title="执行">
                <i class="iconfont icon-start-filled"></i>
              </div>
              <!-- 上传 -->
              <el-upload id="fileInput" :limit="1" :on-progress="handleUpload">
                <div title="上传文件">
                  <i class="iconfont icon-upload-line"></i>
                </div>
              </el-upload>
              <div @click="handleDownload" title="下载文件">
                <i class="iconfont icon-download-line"></i>
              </div>
            </div>
          </div>
          <el-table
            :data="modelData"
            style="
              width: 100%;
              margin-left: 10px;
              display: inline-block;
              height: 530px;
              overflow-y: auto;
            "
          >
            <!-- :height="tableHeight" -->
            <el-table-column
              v-for="(item, index) in modelLabelList"
              :key="index"
              :label="item"
              :prop="item"
              show-overflow-tooltip
              width="100"
            >
            </el-table-column>
          </el-table>
          <mine-pagination
            @numberChange="modelNumberChange"
            :total="modelTotal"
            :page-size="modelPageSize"
            :current-page="modelCurrentPage"
            :layout="'total,prev,pager,next,sizes'"
          >
          </mine-pagination>
        </div>
        <div style="width: 50%">
          <div class="title">
            <div class="run-result">
              <span>运行结果</span>
              <span
                v-if="rowData.resultDesc"
                class="resultDesc"
                :title="rowData.resultDesc"
                >{{ `：(${rowData.resultDesc})` }}</span
              >
            </div>
          </div>
          <!-- 选择诊断时显示内容 -->
          <div class="result-container" v-if="rowData.modelCode == '1'">
            <!-- <console-component></console-component> -->
            <div
              style="
                font-weight: 700;
                font-size: 20px;
                padding: 5px 5px;
                color: rgb(244, 96, 96);
              "
            >
              <span>诊断通过率：</span><span>{{ multiRate }}</span>
            </div>
            <el-table
              class="table"
              :data="resultList"
              style="width: 100%; height: 500px; overflow-y: auto"
              ref="multipleTable"
              v-loading="rightTableLoading"
            >
              <el-table-column label="序号" show-overflow-tooltip width="60">
                <template slot-scope="scope">
                  <span
                    >{{
                      scope.$index +
                      (excuteCurrentPage - 1) * excutePageSize +
                      1
                    }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="真实值" prop="real" show-overflow-tooltip>
              </el-table-column>
              <el-table-column
                label="预测值"
                prop="predict"
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                label="是否通过"
                prop="pass"
                show-overflow-tooltip
              >
              </el-table-column>
            </el-table>
            <mine-pagination
              @numberChange="excuteNumberChange"
              :total="excuteTotal"
              :page-size="excutePageSize"
              :current-page="excuteCurrentPage"
              :layout="'total,prev,pager,next,sizes'"
            >
            </mine-pagination>
          </div>
          <!-- 选择其他时显示内容 -->
          <div class="result-container" v-else>
            <console-component></console-component>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ConsoleComponent from "./Console.vue";
import qs from "qs";
import { QWebChannel } from "@/modules/index/utils/qwebchannel.js";

export default {
  components: { ConsoleComponent },
  name: "TestResult",
  props: {
    rowData: {
      type: Object,
    },
  },
  data() {
    return {
      modelTotal: 0,
      modelPageSize: 10,
      modelCurrentPage: 1,
      modelData: [],
      modelLabelList: [],
      isTempFile: 0,
      excuteTotal: 0,
      excutePageSize: 10,
      excuteCurrentPage: 1,
      resultList: [], // 执行结果
      rightTableLoading: false, // 右边列表加载时
    };
  },
  computed: {
    tableHeight: function () {
      return 0.5 * window.innerHeight + "px";
    },
  },
  methods: {
    // 执行按钮
    async handleExcute() {
      this.getRunResult();
    },
    modelNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.modelPageSize = val.pageSize;
          this.getTestModelTableList();
          break;
        case "currentPage":
          this.modelCurrentPage = val.currentPage;
          this.getTestModelTableList();
          break;
        default:
          break;
      }
    },
    excuteNumberChange(val) {
      switch (val.flag) {
        case "pageSize":
          this.excutePageSize = val.pageSize;
          this.getRunResult();
          break;
        case "currentPage":
          this.excuteCurrentPage = val.currentPage;
          this.getRunResult();
          break;
        default:
          break;
      }
    },
    async getTestModelTableList() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: "/algoTemplateFile/testList",
              RequestMethod: "get",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify(
                {
                  id: _self.rowData.id,
                  page: _self.modelCurrentPage,
                  pageSize: _self.modelPageSize,
                  temp: _self.isTempFile,
                },
                { indices: false }
              ),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              _self.modelLabelList = Object.keys(result?.data.list[0]);
              _self.modelData = result.data.list;
              // 分页功能初始化数据
              _self.modelTotal = result.data.rowCount;
              _self.modelCurrentPage = result.data.page;
            } else {
              _self.$message.warning(result.msg);
            }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          "/algoTemplateFile/testList",
          "get",
          "application/json;charset=UTF-8",
          qs.stringify(
            {
              id: this.rowData.id,
              page: this.modelCurrentPage,
              pageSize: this.modelPageSize,
              temp: this.isTempFile,
            },
            { indices: false }
          ),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            if (res.status === 200) {
              this.modelLabelList = Object.keys(res?.data.list[0]);
              this.modelData = res.data.list;
              // 分页功能初始化数据
              this.modelTotal = res.data.rowCount;
              this.modelCurrentPage = res.data.page;
              // this.modelPageSize = res.data.data.pageSize;
            } else {
              this.$message.warning(res.msg);
            }
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getTestModelTableList", {
          id: this.rowData.id,
          page: this.modelCurrentPage,
          pageSize: this.modelPageSize,
          temp: this.isTempFile,
        });
        if (res.data.status === 200) {
          this.modelLabelList = Object.keys(res?.data.data.list[0]);
          this.modelData = res.data.data.list;
          // 分页功能初始化数据
          this.modelTotal = res.data.data.rowCount;
          this.modelCurrentPage = res.data.data.page;
          // this.modelPageSize = res.data.data.pageSize;
        } else {
          this.$message.warning(res.data.msg);
        }
      }
    },
    // 获取运行结果的数据
    async getRunResult() {
      this.$message.success("开始执行");
      // 先清理原来的数据
      this.$store.commit("CLEAR_RUN_RESULT");
      this.rightTableLoading = true;
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/algoTemplateFile/testAlgo?id=${_self.rowData.id}&temp=${_self.isTempFile}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: qs.stringify({}, { indices: false }),
              isStringParam: true,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            if (!data) {
              console.error("No data received.");
            }
            res = JSON.parse(data);
            const result = res.response || {};
            // update the followings
            if (result.success && res.webInfo.requestId == uuid) {
              if (_self.rowData.modelCode === "1") {
                _self.resultList = result.data.page.list;
                _self.excuteTotal = result.data.page.rowCount;
                _self.multiRate = result.data.rate;
                _self.$message.success("执行成功");
              } else {
                // modelCode为4时，有三种数据形式，分类处理
                if (Array.isArray(result.data)) {
                  result.data.forEach((item) => {
                    _self.$store.commit("SET_RUN_RESULT", item);
                  });
                  return;
                }
                let parseData = JSON.parse(result.data);
                if (Array.isArray(parseData)) {
                  JSON.parse(result.data).forEach((item) => {
                    _self.$store.commit("SET_RUN_RESULT", item);
                  });
                }
                if (
                  Object.prototype.toLocaleString(parseData) ==
                  "[object Object]"
                ) {
                  _self.$store.commit("SET_RUN_RESULT", result.data);
                }
              }
            } else {
              _self.$message.warning(result.msg);
            }
            _self.rightTableLoading = false;
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/algoTemplateFile/testAlgo?id=${this.rowData.id}&temp=${this.isTempFile}`,
          "post",
          "application/json;charset=UTF-8",
          qs.stringify({}, { indices: false }),
          true,
          uuid
        );
        await window.chrome.webview.addEventListener(
          "message",
          (e) => {
            let res = e.data.response;
            if (res.status === 200) {
              if (this.rowData.modelCode === "1") {
                this.resultList = res.data.page.list;
                this.excuteTotal = res.data.page.rowCount;
                this.multiRate = res.data.rate;
                this.$message.success("执行成功");
              } else {
                // modelCode为4时，有三种数据形式，分类处理
                if (Array.isArray(res.data)) {
                  res.data.forEach((item) => {
                    this.$store.commit("SET_RUN_RESULT", item);
                  });
                  return;
                }
                let parseData = JSON.parse(res.data);
                if (Array.isArray(parseData)) {
                  JSON.parse(res.data).forEach((item) => {
                    this.$store.commit("SET_RUN_RESULT", item);
                  });
                }
                if (
                  Object.prototype.toLocaleString(parseData) ==
                  "[object Object]"
                ) {
                  this.$store.commit("SET_RUN_RESULT", res.data);
                }
              }
            } else {
              this.$message.warning(res.msg);
            }
            this.rightTableLoading = false;
          },
          { once: true }
        );
      } else {
        const res = await this.$store.dispatch("getRunStatusResult", {
          id: this.rowData.id,
          temp: this.isTempFile,
          page: this.excuteCurrentPage,
          pageSize: this.excutePageSize,
        });
        // 设置数据
        if (res.data.status === 200) {
          if (this.rowData.modelCode === "1") {
            this.resultList = res.data.data.page.list;
            this.excuteTotal = res.data.data.page.rowCount;
            this.multiRate = res.data.data.rate;
            this.$message.success("执行成功");
          } else {
            res.data.data.forEach((item) => {
              this.$store.commit("SET_RUN_RESULT", item);
            });
          }
        } else {
          this.$message.warning(res.data.msg);
        }
        this.rightTableLoading = false;
      }
    },
    // 执行上传文件
    async handleUpload(uploadFiles, file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = async (e) => {
          formData = e.target.result;
          const uuid = _self.$qwebUtil.generateRandomUUID();
          let sendObject;
          /* eslint-disable-next-line */
          const channel = new QWebChannel(
            window.qt.webChannelTransport,
            async function (channel) {
              sendObject = channel.objects.sendObject;
              // receivedJSON 修改此处发送请求参数
              const receivedJSON = {
                RequestUrl: `/algoTemplateFile/uploadTemp?id=${_self.rowData.id}&temp=${_self.isTempFile}`,
                RequestMethod: "post",
                ContentType: "multipart/form-data",
                RequestBody: {
                  file: formData,
                  fileName: file.name,
                },
                isStringParam: false,
                requestId: uuid,
              };
              await send();
              await _self.$qwebUtil.receive(sendObject, receivedJSON);
              // console.error('received','/feCanvas/pageList')
            }
          );
          /* eslint-disable-next-line */
          async function send() {
            sendObject.sendMessage.connect(function (data) {
              if (!data) {
                console.error("No data received.");
              }
              res = JSON.parse(data);
              const result = res.response || {};
              // update the followings
              if (result.success && res.webInfo.requestId == uuid) {
                // 回显的重新调用当前页面的请求，传字段temp为1
                _self.isTempFile = 1;
                setTimeout(() => {
                  _self.getTestModelTableList();
                }, 200);
                setTimeout(() => {
                  _self.getRunResult();
                }, 400);
                _self.$message.success(result.msg);
              } else {
                _self.$message.warning(result.msg);
              }
            });
          }
        };
      } else if (this.$webview2.isWPF) {
        // 这里对文件的处理需要转成base64的格式后上传
        let reader = new FileReader();
        reader.readAsDataURL(file.raw);
        reader.onload = async (e) => {
          formData = e.target.result;
          const uuid = this.$webview2.generateRandomUUID();
          await this.$webview2.sendWebView2(
            `/algoTemplateFile/uploadTemp?id=${this.rowData.id}&temp=${this.isTempFile}`,
            "post",
            "multipart/form-data",
            {
              file: formData,
              fileName: file.name,
            },
            false,
            uuid
          );
          await window.chrome.webview.addEventListener(
            "message",
            (e) => {
              let res = e.data.response;
              if (res.status === 200) {
                // 回显的重新调用当前页面的请求，传字段temp为1
                this.isTempFile = 1;
                setTimeout(() => {
                  this.getTestModelTableList();
                }, 200);
                setTimeout(() => {
                  this.getRunResult();
                }, 400);
                this.$message.success(res.msg);
              } else {
                this.$message.warning(res.msg);
              }
            },
            {
              once: true,
              capture: true,
            }
          );
        };
      } else {
        const res = await this.$store.dispatch("uploadAlgoFile", {
          file: formData,
          id: this.rowData.id,
          temp: this.isTempFile,
        });
        if (res.data.status === 200) {
          // 回显的重新调用当前页面的请求，传字段temp为1
          this.isTempFile = 1;

          this.getTestModelTableList();
          await this.getRunResult();

          this.$message.success(res.data.msg);
        } else {
          this.$message.warning(res.data.msg);
        }
      }
    },
    // 下载文件
    async handleDownload() {
      let res = {};
      let _self = this;
      if (_self.$qwebUtil.isQtClient) {
        const uuid = _self.$qwebUtil.generateRandomUUID();
        let sendObject;
        /* eslint-disable-next-line */
        const channel = new QWebChannel(
          window.qt.webChannelTransport,
          async function (channel) {
            sendObject = channel.objects.sendObject;
            // receivedJSON 修改此处发送请求参数
            const receivedJSON = {
              RequestUrl: `/algoTemplateFile/downloadTestList?id=${_self.rowData.id}&temp=${_self.isTempFile}`,
              RequestMethod: "post",
              ContentType: "application/json;charset=UTF-8",
              RequestBody: {
                id: _self.rowData.id,
                temp: _self.isTempFile,
              },
              isStringParam: false,
              requestId: uuid,
            };
            await send();
            await _self.$qwebUtil.receive(sendObject, receivedJSON);
            // console.error('received','/feCanvas/pageList')
          }
        );
        /* eslint-disable-next-line */
        async function send() {
          sendObject.sendMessage.connect(function (data) {
            //   if (!data) {
            //     console.error("No data received.");
            //   }
            //   res = JSON.parse(data);
            //   const result = res.response || {};
            //   // update the followings
            //   if (result.success && res.webInfo.requestId == uuid) {
            //     // _self.$message.success("删除成功");
            //     // // await this.loadData(true);
            //     // _self.loadOptionData(
            //     //   true,
            //     //   false,
            //     //   _self.$store.state.dictAdmin.currentDirId
            //     // );
            //   } else {
            //     // _self.$message.error(result.msg || "删除失败");
            //   }
          });
        }
      } else if (this.$webview2.isWPF) {
        const uuid = this.$webview2.generateRandomUUID();
        await this.$webview2.sendWebView2(
          `/algoTemplateFile/downloadTestList?id=${this.rowData.id}&temp=${this.isTempFile}`,
          "post",
          "application/json;charset=UTF-8",
          {
            id: this.rowData.id,
            temp: this.isTempFile,
          },
          false,
          uuid
        );
      } else {
        const res = await this.$store.dispatch("downloadAlgoFile", {
          id: this.rowData.id,
          temp: this.isTempFile,
        });
      }
    },
  },
  created() {
    // 进来先清理
    this.$store.commit("CLEAR_RUN_RESULT");
    this.getTestModelTableList();
    // this.getRunResult();
  },
};
</script>

<style scoped lang="less">
.title {
  display: flex;
  justify-content: space-between;
  padding-left: 20px;
  font-size: 18px;
  font-weight: 700;
  height: 30px;
  line-height: 30px;
  .resultDesc {
    white-space: nowrap;
    overflow: hidden;
    width: 480px;
    text-overflow: ellipsis;
  }
  .run-result {
    display: flex;
  }
  .model-button-group {
    display: flex;
    div {
      margin: 0px 5px;
    }
    .iconfont:hover {
      cursor: pointer;
      font-size: 20px;
      color: #239ce3;
    }
  }
}
/deep/.el-table td {
  padding: 0;
}
/deep/.el-table th {
  padding: 0;
}
</style>